package com.example.administrator.androidros.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.androidros.R;
import com.example.administrator.androidros.activity.DeviceActivity;
import com.example.administrator.androidros.activity.ROSMainActivity;
import com.example.administrator.androidros.activity.RecordActivity;
import com.example.administrator.androidros.activity.SceneActivity;
import com.example.administrator.androidros.adapter.HomePageFunctionAdapter;
import com.example.administrator.androidros.adapter.MessageAdapter;
import com.example.administrator.androidros.base.BaseFragment;
import com.example.administrator.androidros.model.FunctionModel;
import com.example.administrator.androidros.model.MessageModel;
import com.example.administrator.androidros.net.HttpUtils;
import com.example.administrator.androidros.utils.AgentConstants;
import com.example.administrator.androidros.utils.AgentSharedPreferences;
import com.example.administrator.androidros.utils.DisplayHelper;
import com.example.administrator.androidros.utils.ServerConstants;
import com.example.administrator.androidros.widget.CustomPopupMenu;
import com.example.administrator.androidros.widget.CustomTipDialog;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;


/**
 * Created by Administrator on 2018/1/16.
 */

public class HomePageFragment extends BaseFragment {
    private static final String TAG = "hhc";
    @BindView(R.id.fragment_home_page_img_more)
    protected ImageView fragment_home_page_img_more;

    @BindView(R.id.fragment_home_page_banner)
    protected Banner fragment_home_page_banner;

    @BindView(R.id.fragment_home_page_rec_function)
    protected RecyclerView fragment_home_page_rec_function;

    @BindView(R.id.fragment_home_page_rec_notification)
    protected RecyclerView fragment_home_page_rec_notification;

    @BindView(R.id.fragment_home_page_rl_header)
    protected RelativeLayout fragment_home_page_rl_header;

    private List<Integer> moreIconList = new ArrayList<>();//更多
    private List<String> moreTitleList = new ArrayList<>();

    private int[] functionIconList = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};
    private String[] functionTitleList = {"智能设备", "智能场景", "智能监控"};

    private List<String> bannerUrlList = new ArrayList<>();
    private List<String> bannerTitleList = new ArrayList<>();
    List<MessageModel> data = new ArrayList<>();
    private MessageAdapter messageAdapter;

    public static HomePageFragment newInstance() {
        return new HomePageFragment();
    }

    @Override
    protected void initData(View view, Bundle savedInstanceState) {
        setStatusBar();
        initMoreData();
        initBanner();
        initFunction();
        initMessage();
        initRefresh();
        getMessageList();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_page;
    }

    @Override
    protected void onFailure(int requestCode, Object object) {
        stopTipDialog();
    }

    @Override
    protected void onSuccess(int requestCode, Object object) {
        stopTipDialog();
        if (object != null) {
            switch (requestCode) {
                case 1001:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                        getMessageList();
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                case 1002:
                    MessageModel[] deviceModels = (MessageModel[]) HttpUtils.getData(object, MessageModel[].class);
                    if (deviceModels != null) {
                        data = Arrays.asList(deviceModels);
                        messageAdapter.setNewData(data);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context.getApplicationContext())
                    .load(path)
                    .into(imageView);
        }

    }

    protected void setStatusBar() {
        //设置状态栏颜色和位移一段距离
        DisplayHelper.setStatusBarColor(mBaseActivity, R.color.transparent);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) fragment_home_page_rl_header.getLayoutParams();
        lp.setMargins(0, DisplayHelper.getStatusBarHeight(mBaseActivity), 0, 0);
    }

    public void getBannerList() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("applianceMemberId", AgentSharedPreferences.getLastLoginId(mBaseActivity));
        HttpUtils.post(mBaseActivity, 1001, "", jsonObject.toString(), mBaseActivity);
        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_adding), true);
    }

    public void initBanner() {
        float screenWidth = DisplayHelper.getScreenWidth(getActivity());
        float height = screenWidth * 9 / 15;
        fragment_home_page_banner.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) height));
        fragment_home_page_banner.setImages(bannerUrlList)
                .setBannerTitles(bannerTitleList)
//                .setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
                .setImageLoader(new GlideImageLoader())
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
//                        showToast(bannerTitleList.get(position));
                    }
                })
                .start();
    }

    public void initFunction() {
        List<FunctionModel> list = new ArrayList<>();
        for (int i = 0; i < functionIconList.length; i++) {
            FunctionModel functionModel = new FunctionModel();
            functionModel.setImageResource(functionIconList[i]);
            functionModel.setTitle(functionTitleList[i]);
            list.add(functionModel);
        }
//        fragment_home_page_rec_function.setLayoutManager(new LinearLayoutManager(mBaseActivity, LinearLayoutManager.HORIZONTAL, false));
        fragment_home_page_rec_function.setLayoutManager(new GridLayoutManager(mBaseActivity, 3));
        HomePageFunctionAdapter homePageFunctionAdapter = new HomePageFunctionAdapter(R.layout.fragment_home_page_item_function, list);
        homePageFunctionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        Bundle bundle = new Bundle();
                        bundle.putString("title", getString(R.string.device_title));
                        startOtherActivity(DeviceActivity.class, bundle);
                        break;
                    case 1:
                        startOtherActivity(SceneActivity.class, null);
                        break;
                    case 2:
                        startOtherActivity(ROSMainActivity.class, null);
                        break;
                    case 3:
                        startOtherActivity(RecordActivity.class, null);
                        break;
                    default:
                        break;
                }
            }
        });
        fragment_home_page_rec_function.setAdapter(homePageFunctionAdapter);
    }

    public void initMessage() {
        fragment_home_page_rec_notification.setLayoutManager(new LinearLayoutManager(mBaseActivity, LinearLayout.VERTICAL, false));
        messageAdapter = new MessageAdapter(R.layout.message_item, data);
        messageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                final CustomPopupMenu.Builder builder = new CustomPopupMenu.Builder(mBaseActivity);
                builder.setIcon(moreIconList)
                        .setTitle(moreTitleList)
                        .isShowLine(true)
                        .isShowIcon(false)
                        .setItemLayoutParams(-2, -2)
                        .setItemLayoutPadding(10, 10, 20, 20)
                        .setContentView(view)
                        .setOff(-(int) (view.getWidth() / DisplayHelper.DENSITY / 2.5), 0)
                        .setOnMenuItemClickListener(new CustomPopupMenu.onMenuItemClickListener() {
                            @Override
                            public void onMenuItemClick(int itemPosition) {
                                //忽略：messageRead 未读：0 -> 已读：1
                                updateMessageRead(messageAdapter.getData().get(position).getMasterId(),messageAdapter.getData().get(position).getMessageType());
                                builder.dismiss();
                            }
                        })
                        .create()
                        .show();
            }
        });
//        messageAdapter.openLoadAnimation(BaseQuickAdapter.LOADING_VIEW);
//        messageAdapter.isFirstOnly(false);
        fragment_home_page_rec_notification.setAdapter(messageAdapter);
    }

    public void initRefresh() {
//        //设置 Header 为 Material样式
//        fragment_home_page_rec_notification_refreshLayout.setRefreshHeader(new BezierCircleHeader(mBaseActivity));
//        //设置 Footer 为 球脉冲
//        fragment_home_page_rec_notification_refreshLayout.setRefreshFooter(new ClassicsFooter(mBaseActivity));
    }

    public void initMoreData() {
        moreIconList.clear();
        moreIconList.add(R.mipmap.icon_homepage_select);
        moreTitleList.clear();
        moreTitleList.add("忽略");

        bannerUrlList.clear();
        bannerUrlList.add(ServerConstants.FILE_SERVER_URL + "banner4.jpg");
        bannerUrlList.add(ServerConstants.FILE_SERVER_URL + "banner2.jpg");
        bannerUrlList.add(ServerConstants.FILE_SERVER_URL + "banner3.jpg");

        bannerTitleList.clear();
        bannerTitleList.add("");
        bannerTitleList.add("");
        bannerTitleList.add("");
    }

    protected void getMessageList() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("memberId", AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone());
        jsonObject.put("messageType", "10");
        jsonObject.put("messageRead", "0");
        HttpUtils.post(mBaseActivity, 1002, ServerConstants.QUERY_MESSAGE, jsonObject.toString(), this);//主要回调的类
    }

    protected void updateMessageRead(String masterId,String messageType) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("masterId", masterId);
        jsonObject.put("messageType",messageType);
        jsonObject.put("messageRead", "1");
        HttpUtils.post(mBaseActivity, 1001, ServerConstants.UPDATE_MESSAGE, jsonObject.toString(), this);//主要回调的类
    }

    @Override
    public void onResume() {
        super.onResume();
        getMessageList();
    }
}
